#include <stdio.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>

#define FIFO "corepipe"

int main()
{
    int fd = 0;
    int quit_count = 0;
    int retval = -1;
    char buf[1024];
    fd_set wfds;
    struct timeval timeout;


    memset(&timeout, 0x00, sizeof(timeout));
    memset(buf, 0x00, sizeof(buf));

    signal(SIGINT , SIG_IGN );
    fd = open(FIFO, O_WRONLY);
    if(fd < 0)
    {
        perror("open fifo err!");
        return -1;
    }
    printf("open FIFO success! fd = [%d]\n", fd);

    while(1)
    {
        /* Watch stdin (fd 0) to see when it has input. */
        FD_ZERO(&wfds);
        FD_SET(fd, &wfds);

        /* Wait up to five seconds. */
        timeout.tv_sec = 5;
        timeout.tv_usec = 0;
        retval = select(fd + 1, NULL, &wfds, NULL, &timeout);
        /* Don't rely on the value of tv now! */
        if (retval < 0)
        {
            printf("select() err!\n");
            perror("select()");
        }
        else if (retval)
        {
            printf("Data is available now.\n");
            /* FD_ISSET(fd, &wfds) will be true. */
            if( FD_ISSET(fd, &wfds) )
            {
                memset(buf, 0x00, sizeof(buf));
                printf("read from keyboard\n");
                read(0, buf, sizeof(buf) - 1);
                if(strncmp(buf, "quit", 4) == 0)
                {
                    quit_count++;
                    if(quit_count == 2)
                    {
                        printf("exiting!\n");
                        break;
                    }
                }
                write(fd, buf, strlen(buf) - 1);
            }

        }
        else
        {
            printf("No data within five seconds.\n");
        }
    }

    return 0;
}
